/*
 * Filename: GAGameStateHandler.js
 * Author: Abid Hussain
 * Date Modified: 07/06/2011
 * */
var GAXHR = Network.XHR.subclass({
	open: function($super, method, url, async, user, password, overrideNormalize)
	{
		$super(method, url, async, user, password);
		if(overrideNormalize && overrideNormalize == true)
		{
			this.settings.url = url;
		}
	}
});

exports.GAWebFetcher = Core.Class.subclass({

    classname: 'GAWebFetcher',

    initialize: function(delegate, timeout, requestTag) {
        this._delegate = delegate;
        this._timeout = timeout * 1000;
        this.requestTag = requestTag;
        this._abort = false;
        this._timeoutVariable = null;
        this._request = null;
    },
    invokeGetRequest: function(url) {
        this._request = new Network.XHR();
        this._request.onreadystatechange = this._onReadyStateChanged.bind(this);
        this._timeoutVariable = setTimeout(this._requestTimeout.bind(this), this._timeout);
        this._request.open("GET", url, true);
        this._request.send(null);
    },
    invokePostRequest: function(url, data, overrideNormalize) {
    	this._request = new GAXHR();
        this._request.onreadystatechange = this._onReadyStateChanged.bind(this);
        this._timeoutVariable = setTimeout(this._requestTimeout.bind(this), this._timeout);
        this._request.open("POST", url, true,null,null,overrideNormalize); 
        this._request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        if (data == null){ 
            this._request.send("showForm=false");
        }
        else{
            this._request.send(data);
        }
    },
    
    postData: function(baseUrl,params,data){
    	this._makepostbody(baseUrl,params,data);
    },
    _makepostbody: function(baseUrl,params,data)
    {
    	/*var boundary = "---ABlkjasfdkjsdifsdf098asdfa3lka90aflallyourbasekjas09ds0fjasdkal3lj0sa";
    	var newline = '\r\n';
    	var boundaryLine = "--" + boundary + newline;
    	this._postData = params;
    	var body = [];
    	body.push(this._multipartPostBodyFromDataWithBoundary(this._postData, boundary));
    	body.push(boundaryLine);
    	var aname= "gamestate";
    	var fname= "gamestate";
    	var type="application/zip;base64";
    	body.push("Content-Disposition: form-data; name=\"" + aname + "\"; filename=\"" + fname + "\"" + newline);
    	body.push("Content-Type: " + type + newline + newline+"");
    	if(data != null){
    		body.push( data);
    	}
    	body.push(newline);
    	body.push("--" + boundary + "--" + newline);
    	this._postData = body.join("");
    	this._request = new Network.XHR();
    	this._timeoutVariable = setTimeout(this._requestTimeout.bind(this), this._timeout);
    	this._request.open("POST", baseUrl, true,null,null); 
    	this._request.setRequestHeader("Accept", "application/binary-plist, application/zip;base64");    			
    	this._request.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    	this._request.setRequestHeader("Content-Length", ""+this._postData.length);    		
    	this._request.onreadystatechange = this._onReadyStateChanged.bind(this);
   		this._request.send(this._postData);*/
   		
   		var boundary = "---ABlkjasfdkjsdifsdf098asdfa3lka90aflallyourbasekjas09ds0fjasdkal3lj0sa";
    	var newline = '\r\n';
    	var boundaryLine = "--" + boundary + newline;
    	this._postData = params;
    	//Zulu Insertion
    	this._postData.test = data;
    	
    	var body = [];
    	body.push(this._multipartPostBodyFromDataWithBoundary(this._postData, boundary));
    	body.push(boundaryLine);
    	var aname= "gameState";
    	var fname= "gameState";
    	var type="application/zip;base64";
    	body.push("Content-Disposition: form-data; name=\"" + aname + "\"; filename=\"" + fname + "\"" + newline);
    	body.push("Content-Type: " + type + newline + newline+"");
    	if(data != null){
    		body.push( data);
    	}
    	body.push(newline);
    	body.push("--" + boundary + "--" + newline);
    	
    	this._postData = body.join("");
    	this._request = new Network.XHR();
    	this._timeoutVariable = setTimeout(this._requestTimeout.bind(this), this._timeout);
    	this._request.open("POST", baseUrl, true,null,null); 
    	this._request.setRequestHeader("Accept", "application/binary-plist, application/zip;base64");    			
    	this._request.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    	this._request.setRequestHeader("Content-Length", ""+this._postData.length);    		
    	this._request.onreadystatechange = this._onReadyStateChanged.bind(this);
   		this._request.send(this._postData);
    },
    
    _multipartPostBodyFromDataWithBoundary:function (data, boundary){
    	var newline = '\r\n';
    	var boundaryLine = "--" + boundary + newline;
    	var buffer = [];
    	for(var key in data){
    		var value = data[key];
    		buffer.push(boundaryLine);
    		buffer.push("Content-Disposition: form-data; name=\"" + key + "\"" + newline + newline);
    		buffer.push(value);
    		buffer.push(newline);
    	}
    	return buffer.join("");
    },
    
    /* 
     * _onReadyStateChanged: This function checks the response continuously and delegates the  success or failure of request
     * */
    _onReadyStateChanged: function() {
        var authenticated = true;
        try {
        	 if (!this._abort && this._request.readyState == 4) {
                clearTimeout(this._timeoutVariable);
                if (this._request.status == httpStatus.HTTP_STATUS_SUCCESS_OK && this._request.responseText != null) {
                    if (typeof this._delegate.authenticateData === 'function'){ 
                    	authenticated = this._delegate.authenticateData(this._request.responseText);
                    }
                    if (authenticated){ 
                    	this._delegate.webFetchSuccess(this, this._request.responseText);
                    }
                    else{
                    	this._delegate.webFetchFailure(this, httpStatus.HTTP_STATUS_SUCCESS_PARTIAL_CONTENT);
                    }
                } else if (this._request.status == httpStatus.HTTP_STATUS_ZERO && this._request.responseText == null){
                	this._delegate.webFetchFailure(this, httpStatus.HTTP_STATUS_ZERO);
                } else {
                    this._delegate.webFetchFailure(this, (this._request.status == httpStatus.HTTP_STATUS_SUCCESS_OK) ? httpStatus.HTTP_STATUS_SUCCESS_NO_CONTENT : this._request.status);
                }
            }
        } catch (exception) {
        	if(this._delegate != null){
        		this._delegate.webFetchFailure(this,exception);
        	}else 
        	{
        		GALogger.log('this._delegate == null in GAWebfetcher');
        	}
        }
    },
    _requestTimeout: function() {
        this._abort = true;
        this._delegate.webFetchFailure(this, httpStatus.HTTP_STATUS_CLIENT_ERROR_REQUEST_TIMEOUT);
    },
    destroy: function($super) {
    	this._delegate = null;
        this._timeout = null;
        this.requestTag = null;
        this._abort = null;
        this._timeoutVariable = null;
        this._request = null;
        this._postData = null;
    	
    }
    
});
